package com.alawn.security.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alawn.framework.services.security.Resource;
import com.alawn.framework.services.security.Role;
import com.alawn.framework.services.security.User;
import com.alawn.security.mapper.ResourceMapper;
import com.alawn.security.mapper.UserMapper;
import com.alawn.security.service.SecurityService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

@Service
public class SecurityServiceImpl implements SecurityService {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private ResourceMapper resourceMapper;

	@Override
	public User findByUsername(String username) {
		return userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUsername, username));
	}

	@Override
	public Set<String> findRoles(String username) {
		List<Role> roles = userMapper.userHasRole(username);
		Set<String> roleSet = new HashSet<>();
		roles.forEach(role -> {
			if (role != null) {
				roleSet.add(role.getCode());
			}
		});
		return roleSet;
	}

	@Override
	public Set<String> findPermissions(String username) {
		List<Role> roles = userMapper.userHasRole(username);
		Set<String> permissionSet = new HashSet<>();
		roles.forEach(role -> {
			if (role != null) {
				String[] permissions = role.getPermissions().split(",");
				for (String permission : permissions) {
					permissionSet.add(permission);
				}
			}
		});
		return permissionSet;
	}

	@Override
	public List<Resource> hasResources() {
		List<Resource> resources = resourceMapper.selectList(
				new QueryWrapper<Resource>().lambda().isNotNull(Resource::getUrl).isNotNull(Resource::getPermission));
		return resources;
	}
}
